<?php
namespace Ktnw\sms\utils;
use Illuminate\Config\Repository;
use Illuminate\Filesystem\Filesystem;
use Ktnw\sms\SmsApplication;

/**
 * 加载配置文件
 */
class Config extends Repository
{

    public function __construct()
    {
        parent::__construct();
        $this->loadConfigResource();
    }

    /**
     * @param string path
     */
    private function loadConfigResource()
    {
        $path       = __DIR__ . '/../../resources/';
        $filesystem = new Filesystem();
        if (!$filesystem->isDirectory($path)) {
            return;
        }
        foreach ($filesystem->allFiles($path) as $file) {
            $relativePathname = $file->getRelativePathname();
            $pathInfo         = pathinfo($relativePathname);
            if ($pathInfo['dirname'] == '.') {
                $key = $pathInfo['filename'];
            } else {
                $key = str_replace('/', '.', $pathInfo['dirname']) . '.' . $pathInfo['filename'];
            }
            $this->set($key, require $path . '/' . $relativePathname);
        }
    }

    /**
     * 获取配置文件
     * @param $key
     * @param mixed $default
     * @return mixed
     */
    public static function getConfigValue($key, $default = '')
    {
        if (function_exists('config')) {
            return config($key);
        }

        $config = SmsApplication::getInstance(Config::class);
        return $config->get($key);
    }
}